import { useEffect, useState } from 'react';
import tools from './components';
import styles from './index.module.less';
import { Format, getFormatStr, getNextFormat } from './weapon';

// 经度（正:东经E; 负:西经W）
// 纬度（正:北纬N; 负:南纬S）

const { DDD, DMS, DM, NWSE } = tools;

export type FormatValue = (typeof Format)[keyof typeof Format];

type CoordinateTransProps = {
  maximum: number;
  minimum: number;
  value: number | null;
  units: string[];
  onChange: (val: number | null) => void;
  showFormat?: FormatValue;
  showFormatChangeBtn?: boolean;
  onFormatChange?: (format: FormatValue) => void;
};

const CoordinateTrans = (props: CoordinateTransProps) => {
  const {
    maximum,
    minimum,
    value,
    units,
    onChange,
    showFormat = Format.DDD,
    showFormatChangeBtn = false,
    onFormatChange,
  } = props;

  const [dddValue, setValue] = useState<number | null>(null);

  const onChanged = (val: number | null) => {
    if (val) {
      onChange(Number(val));
      setValue(Number(val));
    } else {
      onChange(val);
      setValue(null);
    }
  };

  useEffect(() => {
    if (value !== null) {
      setValue(Number(value.toFixed(6)));
    } else {
      setValue(null);
    }
  }, [value]);

  return (
    <div className={styles.root}>
      <DDD
        className={`${styles.container} ${showFormat === Format.DDD ? null : styles.hide}`}
        maximum={maximum}
        minimum={minimum}
        value={dddValue}
        onChange={onChanged}
      />
      <DMS
        className={`${styles.container} ${showFormat === Format.DMS ? null : styles.hide}`}
        maximum={maximum}
        minimum={minimum}
        units={units}
        value={dddValue}
        onChange={onChanged}
      />
      <DM
        className={`${styles.container} ${showFormat === Format.DM ? null : styles.hide}`}
        maximum={maximum}
        minimum={minimum}
        units={units}
        value={dddValue}
        onChange={onChanged}
      />
      <NWSE
        className={`${styles.container} ${showFormat === Format.NWSE ? null : styles.hide}`}
        maximum={maximum}
        minimum={minimum}
        units={units as [string, string]}
        value={dddValue}
        onChange={onChanged}
      />
      {showFormatChangeBtn && (
        <div
          className={styles.switch}
          onClick={() => {
            onFormatChange?.(getNextFormat(showFormat));
          }}
        >
          {getFormatStr(showFormat)}
        </div>
      )}
    </div>
  );
};

export default CoordinateTrans;
